﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Flower.Client;
using Flower.Directory.Host.Default;
using Flower.Directory.Util;
using Flower.Services;
using Flower.Services.Data;
using Flower.Testing;
using Flower.Workflow;
using NUnit.Framework;
using Process = Flower.Services.Data.Process;
using SortOrder = Flower.Services.Data.SortOrder;

namespace Flower.Directory.Management.Tests
{
    [TestFixture]
    public class ImportExportTests
    {
        private const string EXPORT_PATH = "Export";
        private const string EXPORT_PATH_ZIP = "Export.zip";

        [DataContract]
        public class MyProcessState : Workflow.Process
        {
            [DataMember]
            public string DataMember { get; set; }

            public void DefineProcess(IProcessBuilder process)
            {
            }
        }

        [Test]
        public void ExportImport()
        {
            var dir = new MemoryDirectory.Directory(new ScriptEnginePool(1));

            var state =
                new MyProcessState 
                {
                    DataMember = "Data"
                };

            string pid;
            
            new DirectoryBuilder(dir)
                .Root("/Assemblies")
                    .Assembly("MyAssembly", new byte[] { 1, 2, 3 }).End()
                .End()
                .Root("/Services")
                    .ServiceContainer("MyServiceContainer", (1).ToBlob(BlobFormat.BinXml)).End()
                .End()
                .Root("/Workflows")
                    .Workflow("MyWorkflow", "MyWorkflowDefinition", new[] { "proc1", "proc2", "proc3" }).End()
                .End()
                .Root("/Processors")
                    .Processor("MyProcessor", (1).ToBlob(BlobFormat.BinXml))
                        .Process("Workflow", out pid)
                            .State(state).End()
                        .End()
                    .End()
                .End()
                .Root("/Processes")
                    .Link("MyLink", pid).End()
                .End()
                .Root("/Sets/Shared")
                    .Set("MySet", typeof(int).AssemblyQualifiedName, 10)
                        .Message("MyMessage", BlobFormat.BinXml, 1).End()
                    .End()
                .End()
                .Root("/Roles/Application")
                    .Role("MyApp", new[] { "user1", "user2", "user3" }).End()
                .End();

            if (System.IO.Directory.Exists(EXPORT_PATH))
            {
                System.IO.Directory.Delete(EXPORT_PATH, true);
            }

            dir.ExportToFileSystem(EXPORT_PATH, DirectoryEntryTypes.All);

            var newDir = new MemoryDirectory.Directory(new ScriptEnginePool(1));
            IDictionary<string, string> idsMapping = newDir.ImportFromFileSystem(EXPORT_PATH);
            DoChecks(newDir, idsMapping, pid);

            if (System.IO.File.Exists(EXPORT_PATH_ZIP))
            {
                System.IO.File.Delete(EXPORT_PATH_ZIP);
            }

            dir.ExportToArchive(EXPORT_PATH_ZIP, DirectoryEntryTypes.All);

            newDir = new MemoryDirectory.Directory(new ScriptEnginePool(1));
            idsMapping = newDir.ImportFromArchive(EXPORT_PATH_ZIP);
            DoChecks(newDir, idsMapping, pid);
        }

        private static void DoChecks(IDirectory newDir, IDictionary<string, string> idsMapping, string pid)
        {
            var assembly = newDir.Get("/Assemblies/MyAssembly") as Assembly;
            Assert.IsNotNull(assembly);
            Assert.IsTrue(assembly.Image[0] == 1 && assembly.Image[1] == 2 && assembly.Image[2] == 3);

            var serviceContainer = newDir.Get("/Services/MyServiceContainer") as ServiceContainer;
            Assert.IsNotNull(serviceContainer);
            Assert.IsTrue(serviceContainer.Configuration.To<int>() == 1);

            var workflow = newDir.Get("/Workflows/MyWorkflow") as Services.Data.Workflow;
            Assert.IsNotNull(workflow);
            Assert.AreEqual("MyWorkflowDefinition", workflow.DefinitionType);
            Assert.IsTrue
            (
                workflow.PreferredProcessors.Contains("proc1") &&
                workflow.PreferredProcessors.Contains("proc2") &&
                workflow.PreferredProcessors.Contains("proc3")
            );

            var processor = newDir.Get("/Processors/MyProcessor") as Processor;
            Assert.IsNotNull(processor);
            Assert.IsTrue(processor.Configuration.To<int>() == 1);

            var process = newDir.Get(idsMapping[pid]) as Process;
            Assert.IsNotNull(process);
            Assert.AreEqual("Workflow", process.Workflow);

            var stateEnt = newDir.GetChildren("/Processors/MyProcessor/" + idsMapping[pid], DirectoryEntryTypes.State, SortProperty.Default, SortOrder.Asc, 0, 1)[0] as State;
            Assert.IsNotNull(stateEnt);
            var stateEntState = stateEnt.Data.To<MyProcessState>();
            Assert.IsTrue(stateEntState.DataMember == "Data");

            var link = newDir.Get("/Processes/MyLink") as Link;
            Assert.IsNotNull(link);
            Assert.AreEqual(idsMapping[pid], link.Target);

            var set = newDir.Get("/Sets/Shared/MySet") as Set;
            Assert.IsNotNull(set);
            Assert.AreEqual(typeof(int).AssemblyQualifiedName, set.MessageType);
            Assert.AreEqual(10, set.Capacity);

            var message = newDir.Get("/Sets/Shared/MySet/MyMessage") as Message;
            Assert.IsNotNull(message);
            Assert.AreEqual(1, message.Data.To<int>());

            var role = newDir.Get("/Roles/Application/MyApp") as Role;
            Assert.IsNotNull(role);
            Assert.IsTrue(role.Users.Contains("user1") && role.Users.Contains("user2") && role.Users.Contains("user3"));
        }
    }
}
